package com.duowan.cms.service.parser;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

/**
 * 模板工厂类
 * 
 * @author Administrator
 */
public class VMFactory {
    
    private static Logger logger = Logger.getLogger(VMFactory.class);
    
    private String templatebody = null;
    private Template tpl = null;
    private VelocityContext context = null;
    private static VelocityEngine engine = new VelocityEngine();
    private String ret_error = "";

    static {
        init();
    }

    public VMFactory() {
        context = new VelocityContext();
    }

    public static void init() {
    	try {
    	    engine.init();
    	} catch (Exception e) {
    	    logger.error("VMFactory init error:",e);
    	}
    }

//    public void setTemplate(String templatefile) {
//    	try {
//    	    tpl = engine.getTemplate(templatefile, "GBK");
//    	} catch (Exception e) {
//    	    logger.error("setTemplate error,templatefile="+templatefile,e);
//    	}
//    	this.templatebody = null;
//    }

    public void setTemplateBody(String templatebody) {
    	try {
    	    this.templatebody = templatebody;
    	    this.tpl = null;
    	} catch (Exception e) {
    	    logger.error("setTemplateBody error,templatebody="+templatebody,e);
    	}
    }

    public void put(String name, Object obj) {
        context.put(name, obj);
    }

    public String toString() {
    	StringWriter out = new StringWriter();
    	try {
    	    output(out);
    	    return out.toString();
    	} catch (Exception e) {
    	    logger.warn("toString error:",e);
    	    return "";
    	} finally {
    	    try {
    		out.close();
    	    } catch (Exception e) {
    		logger.warn("out.close error:",e);
    	    }
    	}
    }

    public String getError() {
    	return ret_error;
    }
    
    public void setError(String error){
    	this.ret_error = error;
    }

    public void output(Writer out) throws IOException {
		try {
		    if (this.tpl != null) {
				tpl.merge(context, out);
		    } else {
				engine.evaluate(context, out, "", templatebody);
		    }
		} catch (Exception e) {
		    ret_error = e.toString();
		    logger.warn("output error:",e);
		}
    }
}
